package com.slaffka.dao;

import com.slaffka.action.UserAction;
import com.slaffka.action.UserSetting;
import com.slaffka.model.Filial;
import com.slaffka.model.Loan;
import com.slaffka.model.User;

import javax.ejb.Stateful;
import javax.faces.bean.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Scope;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: slaffka
 * Date: 21.11.12
 * Time: 23:45
 * To change this template use File | Settings | File Templates.
 */
@Named("loanDAO")
@ApplicationScoped
public class LoanDAO implements Serializable {

    @PersistenceContext
    EntityManager entityManager;

    @Inject
    UserAction userAction;

    @Inject
    UserSetting userSetting;

    @Inject
    FilialDAO filialDAO;


    public List<Loan> getLoanList(){
        User currentUser = userSetting.getCurrentUser();
        if (currentUser == null){
            return null;
        }
        String queryStr = "select l from Loan l where l.finishDate is null ";
        Filial filial = currentUser.getFilial();
        if (filial != null && !"multiFilial".equals(filial.getAbbreviation())){
            queryStr += "and l.filial = :filial";
        }
        Query query = getEntityMananger().createQuery(queryStr);
        if (filial != null && !"multiFilial".equals(filial.getAbbreviation())){
            query.setParameter("filial", filial);
        }
        return query.getResultList();
    }

    public List<Loan> getLoanInPeriod(Date dateStart, Date dateEnd){
        return entityManager.createQuery("select l from " +
                        "Loan l " +
                        "where l.createDate < :dateEnd " +
                        "and (l.finishDate >= :dateStart or l.finishDate is null ) ")
                        .setParameter("dateEnd", dateEnd)
                        .setParameter("dateStart", dateStart)
                        .getResultList();
    }

    private EntityManager getEntityMananger(){

        return entityManager;
    }

    public void addNewLoan(Loan loan) {
        if (loan.getContractId() != null){
            entityManager.merge(loan);
        } else {
            entityManager.persist(loan);
        }
//        filialDAO.recalculateMultiFilialAmount();
        entityManager.flush();
    }

    /**
     * Метод заверщает займ на текущий день. Т.е. заниматель приносит ровно столько денег сколько он должен на текущий день
     * @param loan - займ который необходимо завершить
     */
    public void finishLoan(Loan loan) {
        try {
            entityManager.refresh(loan);

            Double finishAmount = loan.getCurrentAmount();
            Double newCapital = loan.getFilial().getCapital() + loan.getFeeForUseOfFunds();

            loan.setFinishDate(new Date());
            loan.setFinishAmount(finishAmount);

            filialDAO.updateCapitalFilial(loan.getFilial().getFilialId(), newCapital);

            entityManager.merge(loan);
            entityManager.flush();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<Loan> getAllLoansForCurrentFilial() {
        User currentUser = userSetting.getCurrentUser();
        if (currentUser == null){
            return null;
        }
        String queryStr = "select l from Loan l where 1 = 1 ";
        Filial filial = currentUser.getFilial();
        if (filial != null && !"multiFilial".equals(filial.getAbbreviation())){
            queryStr += "and l.filial = :filial";
        }
        Query query = getEntityMananger().createQuery(queryStr);
        if (filial != null && !"multiFilial".equals(filial.getAbbreviation())){
            query.setParameter("filial", filial);
        }
        return query.getResultList();
    }
}
